import hashlib
from flask import Blueprint, make_response, request
from utils.utils import return_model
from query.admin_query import find_one_admin
from utils.index import request_get, return_format
from query.message_query import add_one_message,pagination_query,find_count



message = Blueprint('message', __name__)

@message.route("/add_message", methods=['POST'])
def add_message():
    cookie_id = request.cookies.get('cookie_id')
    # 如果cookie为空则该用户未登录
    if cookie_id is None:
        return make_response((return_format("请您登录以后再进行评论!", None, 204)))
    # 如果cookie不为空则查询该cookie_id获取用户的id
    find_one_data = find_one_admin({"cookie_id": cookie_id})
    if find_one_data["msg"]== "error":
        return make_response((return_format("查询失败!", None, 500)))
    if find_one_data["msg"] == "success":
        admin_data = find_one_data["data"].admin_to_dict()
        message.info = {
            "message": request_get("message"),
            "time": request_get("time"),
            "admin_id": admin_data["id"]
        }
        add_one_data = add_one_message(message.info)
        if add_one_data["msg"]== "error":
            return make_response((return_format("评论失败!", None, 500)))
        if add_one_data["msg"]== "success":
            return make_response((return_format("评论成功!", None, 200)))



@message.route("/paging", methods=['POST'])
def paging():
    count = find_count()
    if count["msg"] == "error":
        return make_response((return_format("查询评论总数失败!", {"count": 0}, 500)))
    page_number = request_get("page_number")
    page_size = request_get("page_size")
    message_data = pagination_query(page_number = page_number, page_size = page_size)
    if message_data["msg"] == "error":
        return make_response((return_format("查询评论失败!", {"count": 0}, 500)))
    if message_data["msg"] == "success":
        message_list = []
        for item in message_data["data"]:
            msg = item.message_to_dict()
            admin = item.admin.admin_to_dict()
            data = {
                "id": msg["id"],
                "message" : msg["message"],
                "time": msg["time"],
                "user_name": admin["user_name"],
                "user_img": admin["user_img"],
            }
            message_list.append(data)
        return make_response((return_format("查询评论成功!", {"count": count["data"],"message_list":message_list,"page_number":page_number,"page_size":page_size}, 200)))

@message.route("/get_count", methods=['POST'])
def get_count():
    count = find_count()
    if count["msg"] == "error":
        return make_response((return_format("查询评论总数失败!", {"count": 0}, 500)))
    if count["msg"] == "success":
        return make_response((return_format("查询评论总数成功!", {"count": count["data"]}, 200)))